package cn.ziyoufa.smart.smartschool.manager;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.ziyoufa.smart.smartschool.R;
import cn.ziyoufa.smart.smartschool.net.GetAndroidVersionNet;
import cn.ziyoufa.smart.smartschool.webview.route.Router;

/**
 * 创建人 ： 赵泽东
 * 创建时间：2018/9/30
 *
 * @param
 * @param
 */
public class UpdateManager extends Activity {
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };

    private ProgressBar mProgressBar;
    private Dialog mDownloadDialog;

    private String mSavePath;
    private int mProgress;

    private boolean mIsCancel = false;

    private static final int DOWNLOADING = 1;
    private static final int DOWNLOAD_FINISH = 2;

//	private static final String PATH = Config.SERVER_VERSION;

    private String mVersion_code;//当前版本号
    private String mVersion_name;//版本名称
    private String mVersion_desc;//新版本的文字说明
    private String mVersion_path;//下载地址

    public static final int INSTALL_REPLACE_EXISTING = 0x00000002;

    private Context mContext;

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    public UpdateManager(Context context) {
        mContext = context;
    }

    private Handler mGetVersionHandler = new Handler(){
        public void handleMessage(Message msg) {
            JSONObject jsonObject = (JSONObject) msg.obj;
            try {
                Boolean status = jsonObject.getBoolean("status");
                if(status){
                    JSONObject json = jsonObject.getJSONObject("data");
                    if(json != null){
                        mVersion_code = json.getString("ele_version_code");
                        mVersion_name = json.getString("ele_version_name");
                        mVersion_desc = json.getString("ele_version_desc");
                        mVersion_path = Router.WEB_ROOT+json.getString("ele_version_path");

                        if (isUpdate()){
                            Toast.makeText(mContext, "需要更新", Toast.LENGTH_SHORT).show();
//                    // 显示提示更新对话框
//                    showNoticeDialog();
                            downloadAPK();// 下载文件
                        } else{
                            Toast.makeText(mContext, "已是最新版本", Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(mContext, "已是最新版本", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(mContext, "已是最新版本", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        };
    };

    private Handler mUpdateProgressHandler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what){
                case DOWNLOADING:
                    // 设置进度条
                    mProgressBar.setProgress(mProgress);
                    break;
                case DOWNLOAD_FINISH:
                    // 隐藏当前下载对话框
//                    mDownloadDialog.dismiss();
                    // 安装 APK 文件
                    installAPK();
            }
        };
    };

    /*
     * 检测软件是否需要更新
     */
    public void checkUpdate() {
        new GetAndroidVersionNet(mContext,new GetAndroidVersionNet.SuccessCallback(){

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject object = new JSONObject(result);
                    Message msg = Message.obtain();
                    msg.obj = object;
                    mGetVersionHandler.sendMessage(msg);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        },new GetAndroidVersionNet.FailCallback(){

            @Override
            public void onFail() {

                Toast.makeText(mContext, R.string.fail_to_loading, Toast.LENGTH_LONG).show();
            }
        });
    }

    /*
     * 与本地版本比较判断是否需要更新
     */
    protected boolean isUpdate() {
        int serverVersion = Integer.parseInt(mVersion_code);
        int localVersion = 1;
        try {
            localVersion = mContext.getPackageManager().getPackageInfo("cn.ziyoufa.smart.smartschool", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        if (serverVersion > localVersion)
            return true;
        else
            return false;
    }

    /*
     * 有更新时显示提示对话框
     */
    protected void showNoticeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        String message = "软件有更新，要下载安装吗？\n" + mVersion_desc;
        builder.setMessage(message);

        builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 隐藏当前对话框
                dialog.dismiss();
                // 显示下载对话框
                showDownloadDialog();
            }
        });

        builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 隐藏当前对话框
                dialog.dismiss();
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });

        builder.create().show();
    }

    /*
     * 显示正在下载对话框
     */
    protected void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("下载中");
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_progress, null);
        mProgressBar = (ProgressBar) view.findViewById(R.id.id_progress);
        builder.setView(view);

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 隐藏当前对话框
                dialog.dismiss();
                // 设置下载状态为取消
                mIsCancel = true;
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });

        mDownloadDialog = builder.create();
        mDownloadDialog.show();

        // 下载文件
        downloadAPK();
    }

    /*
     * 开启新线程下载文件
     */
    private void downloadAPK() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//                        String sdPath = Environment.getExternalStorageDirectory() + "/";
                        mSavePath = "storedownload";
                        //修改SD卡上的文件或目录名
                        String[]  s=mSavePath.split("/");
                        String str=Environment.getExternalStorageDirectory().toString();
                        for (int i = 0; i < s.length; i++) {
                            str=str+"/"+s[i];
                            File file=new File(str);
                            if(!file.exists()){
                                file.mkdir();
                            }
                        }

                        //下载后的文件名
                        String fileName = str + "smartSchool.apk";
                        File file1 = new File(fileName);
                        if (file1.exists()) {
                            file1.delete();
                        }
                        mSavePath = str;
                        // 下载文件
                        HttpURLConnection conn = (HttpURLConnection) new URL(mVersion_path).openConnection();
                        conn.connect();
                        InputStream is = conn.getInputStream();
                        int length = conn.getContentLength();

                        File apkFile = new File(mSavePath, "smartSchool.apk");
                        FileOutputStream fos = new FileOutputStream(apkFile);

                        int count = 0;
                        byte[] buffer = new byte[1024];
                        while (!mIsCancel){
                            int numread = is.read(buffer);
                            count += numread;
                            // 计算进度条的当前位置
//                            mProgress = (int) (((float)count/length) * 100);
                            // 更新进度条
//                            mUpdateProgressHandler.sendEmptyMessage(DOWNLOADING);

                            // 下载完成
                            if (numread < 0){
                                mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                                break;
                            }
                            fos.write(buffer, 0, numread);
                        }
                        fos.close();
                        is.close();
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /*
     * 下载到本地后执行安装
     */
    protected void installAPK() {
        File apkFile = new File(mSavePath, "smartSchool.apk");
        if (!apkFile.exists())
            return;
//        openFile(apkFile, mContext);
        install(apkFile);
    }

    private void install(File file) {
        PackageManager mPm = mContext.getPackageManager();
        Class<?> paramTypes[] = getParamTypes(mPm.getClass(), "installPackage");
        try {
            Method method = mPm.getClass().getMethod("installPackage", paramTypes);
            method.invoke(mPm, Uri.fromFile(file),null,INSTALL_REPLACE_EXISTING,"cn.ziyoufa.smart.smartschool");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Class<?>[] getParamTypes(Class<?> cls, String mName) {
        Class<?> cs[] = null;
        Method[] mtd = cls.getMethods();
        for (int i = 0; i < mtd.length; i++) {
            if (!mtd[i].getName().equals(mName)) {
                continue;
            }

            cs = mtd[i].getParameterTypes();
        }
        return cs;
    }

    /**
     * 调用系统安装
     * @param file
     * @param context
     */
    private void openFile(File file, Context context) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        String type = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        try {
            context.startActivity(intent);
        } catch (Exception var5) {
            var5.printStackTrace();
            Toast.makeText(context, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }

    }
    public String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }

}
